<template>
  <div>
    <!-- 标题和输入框显示在一行 -->
    <el-form :model="order" label-width="80px" label-position="left">
      <el-form-item label="标题:">
        <el-input
          v-model="order.orderTitle"
          placeholder="请输入标题"
        ></el-input>
      </el-form-item>

      <el-form-item label="游戏类型:">
        <el-select
          v-model="order.gameTypeId"
          placeholder="请选择游戏类型"
          @change="handleGameTypeChange"
        >
          <el-option
            v-for="game in games"
            :key="game.id"
            :label="game.gameTypeName"
            :value="game.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 价格和单位在同一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="价格:">
            <el-input
              v-model="order.orderPrice"
              placeholder="请输入价格"
              @input="handlePriceInput"
              oninput="value=value.replace(/[^\d]/g,'')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则:">
            <el-radio-group v-model="order.orderUnit">
              <el-radio label="0">局</el-radio>
              <el-radio label="1">小时</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 发布订单图片 -->
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="handleFileChange"
      :auto-upload="false"
      ref="upload"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-button type="primary" @click="confirmOrder">确认发布</el-button>
  </div>
</template>

<script>
import bossApi from "@/http/bossApi";
import playmateApi from "@/http/playmateApi";
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      order: {
        id: null,
        tenantId: 1, // 注意：您的实体类中是 Long 类型
        playmateId: null,
        orderTitle: "",
        gameTypeId: null,
        orderUnit: 0, // 注意：您的实体类中是 Integer 类型
        orderPrice: 0, // 注意：您的实体类中是 Double 类型
        orderBuyNumber: 0, // 注意：您的实体类中是 Integer 类型
        orderGiftNumber: 0,
        orderStatus: 0, // 已发布状态
      },
      games: [],
      fileList: [],
    };
  },
  methods: {
    //发布订单
    confirmOrder() {
      // 创建 FormData 对象
      const formData = new FormData();

      // 添加订单信息（作为JSON字符串）
      formData.append("order", JSON.stringify(this.order));

      // 添加文件
      this.fileList.forEach((file) => {
        formData.append("images", file.raw);
      });

      // 发送请求
      playmateApi
        .publishOrder(formData)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("订单发布成功");
            this.resetForm();
          } else {
            this.$message.error(res.message || "订单发布失败");
          }
        })
        .catch((err) => {
          console.error("订单发布失败:", err);
          this.$message.error("网络错误，请重试");
        });
    },

    // 处理文件变化
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },

    handleRemove(file, fileList) {
      console.log("删除文件:", file);
      console.log("当前文件列表:", fileList);
      this.fileList = fileList;
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url || file.response?.data || "";
      this.dialogVisible = true;
    },

    handleGameTypeChange(value) {
      console.log("选中的游戏类型ID:", value);
    },

    // 价格输入处理方法
    handlePriceInput(value) {
      // 使用正则表达式只保留数字
      this.order.orderPrice = value.replace(/[^\d]/g, "");
    },

    // 重置表单
    resetForm() {
      this.order = {
        id: null,
        tenantId: 1,
        playmateId: null,
        orderTitle: "",
        gameTypeId: null,
        orderUnit: 0,
        orderPrice: 0,
        orderBuyNumber: 0,
        orderGiftNumber: 0,
        orderStatus: 0,
      };
      this.fileList = [];
      this.$refs.upload.clearFiles();
    },

    getAllGameType() {
      bossApi
        .getAllGameType({
          tenantId: this.order.tenantId,
        })
        .then((res) => {
          if (res.code != 200) {
            this.$message.error(res.message);
            return;
          }
          this.games = res.data;
        });
    },
  },
  created() {
    this.getAllGameType();

    // 从本地存储获取用户信息
    const userStr = localStorage.getItem("user");
    if (userStr) {
      const user = JSON.parse(userStr);
      this.order.playmateId = user.id;
    }
  },
};
</script>
